<template>
  <view class="add-type">
    <wd-popup v-model="show" position="top">
      <BaseForm
        :form="form"
        :form-list="formList"
        :rules="rules"
        @commit="commit"
      />
    </wd-popup>
  </view>
</template>

<script setup>
import { ref } from "vue";

import {
  addClothesTypeList,
  updateClothesTypeList,
} from "../../api/clothes/type";
import { toast } from "../../utils/common";

const show = ref(false);

const emits = defineEmits(["addFinished"]);
async function commit() {
  let res;
  let params = { ...form.value };
  params.second_category = params.second_category.replace(/，/g, ",");
  if (params.second_category[params.second_category.length - 1] === ",") {
    params.second_category = params.second_category.slice(
      0,
      params.second_category.length - 1
    );
  }
  res = params.id
    ? await updateClothesTypeList(params)
    : await addClothesTypeList(params);
  if (res.code === 0) {
    emits("commitFinished");
    for (const k in form.value) {
      form.value[k] = "";
    }
    show.value = false;
  } else {
    toast({
      icon: "error",
      title: res.message,
    });
  }
}

const form = ref({});
const formList = [
  {
    label: "一级分类名称",
    prop: "first_category",
    labelWidth: 100,
  },
  {
    label: "二级分类名称",
    prop: "second_category",
    placeholder: '多个二级分类以","分隔，若无则不填',
    labelWidth: 100,
  },
];
const rules = ref({
  first_category: [{ required: true, message: "请填写一级分类" }],
});

defineExpose({
  show,
  form,
});
</script>

<style scoped lang="scss">
.add-type {
  .footer {
    padding: 24rpx;
    box-sizing: border-box;
    width: 100%;
    justify-content: space-between;
  }
}
</style>
